package threading;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Microsoft
 * Date: 2023-07-14
 * Time: 14:41
 */
//就不写泛型了，假定存储的元素是int
//基于数组来实现阻塞队列
class MyBlockingQueue {
    //实现阻塞队列，分三步
    //1.先实现一个普通队列
    //2.加上线程安全
    //3.加上阻塞功能
    private int[] items = new int[1000];
    //约定[head,tail)队列的有效元素
    volatile private int head = 0;
    volatile private int tail = 0;
    volatile private int size = 0;

    //入队列
    synchronized public void put(int elem) throws InterruptedException {
        while (size == items.length) {
            //队列满了，阻塞等待
            this.wait();
        }
        //把新元素放到tail所在位置
        items[tail] = elem;
        tail++;
        //如果tail到了末尾，就需要让tail回到0位置
        if (tail == items.length) {
            tail = 0;
        }
        size++;
        this.notify();//唤醒下面出队列阻塞等待的情况
    }

    //出队列
    synchronized public Integer take() throws InterruptedException {
        while (size == 0) {
            this.wait();//空了阻塞等待
        }
        int value = items[head];
        head++;
        if (head == items.length) {
            head = 0;
        }
        size--;
        this.notify();//唤醒上述入队列的wait
        return value;
    }
}
public class ThreadDemo21 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue();
        //消费者
        Thread t1 = new Thread(() -> {
            while (true) {
                try {
                    int value = queue.take();
                    System.out.println("消费元素" + value);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });

        //生产者
        Thread t2 = new Thread(() -> {
            int value = 0;
            while (true) {
                try {
                    System.out.println("生产元素" + value);
                    queue.put(value);
                    value++;
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        t1.start();
        t2.start();
    }
}








































